package com.smartian.scan.filesearch.impl.engine;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.smartian.scan.filesearch.bean.PathFile;
import com.smartian.scan.filesearch.bean.SearchResult;
import com.smartian.scan.filesearch.interfaces.ISearchTaskEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MediaStoreQueryTaskEngine implements ISearchTaskEngine {

    public static final String QUERY_PATH = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString();
    private Context context;

    public MediaStoreQueryTaskEngine(Context context) {
        this.context = context;
    }

    public static ISearchTaskEngine getQueryEngine(Context context, String path) {
        if(!QUERY_PATH.equals(path)) return null;
        return new MediaStoreQueryTaskEngine(context);
    }

    @Override
    public SearchResult doInBackground(String dir) {

        if(!MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString().equals(dir)){
            return new SearchResult(new ArrayList<PathFile>(),new ArrayList<PathFile>());
        }
        List<PathFile> mediaFiles = queryMediaStorage(this.context);
        return new SearchResult(mediaFiles,new ArrayList<PathFile>());
    }


    public static List<PathFile> queryMediaStorage(Context context) {
        Context ctx = context.getApplicationContext();
        Cursor cursor = MediaStore.Images.Media.query(ctx.getContentResolver(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null);
        List<PathFile> pictures = new ArrayList<>();
        if (null == cursor) {
            return pictures;
        }
        try {
            do{
                if (!cursor.moveToNext()) {
                     break;
                }
                int index = -1;
                String path = null;
                index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                if (index >= 0) {
                    path = cursor.getString(index);
                }
                if (TextUtils.isEmpty(path)) {
                    continue;
                }
                File file = new File(path);
                if (!file.exists() || !file.isFile()) {
                    continue;
                }

                pictures.add(PathFile.build(file,QUERY_PATH));

            }while (true);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }

        return pictures;
    }
}
